<template>
  <div class="echarts-wrap-fck pos-rel">
    <div class="mask-line pos-abs"></div>
    <div class="echarts-wrap" id="chart-container-outter" name="chart-container-outter">
        <!-- <div id="chart-container"></div> -->
    </div>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { rawData } from './data'
  import * as API from '@/api/index.js'
  import '@/utils/date'
  export default {
    name: 'Home',
    components: {
    },
    data() {
      return {
        dom: null,
        lastTime: 0,
        myChart: null,
        params: {
          instId: 'ETH-USD',
          after: '', // 时间戳之前的数据
          before: '', // 时间戳之后的数据
          bar: '1m', // 时间粒度
          limit: '300'
        },
        lengend: {
          '1m': '分时'
        }
      }
    },
    computed: {
      ...mapGetters([
        'candleType'
      ])
    },
    watch: {
      'candleType': function(newVal) {
        console.log('echart.vue==>>watch.candleType, newVal: %o', newVal)
        this.clearOptionData()
        this.initPrevData()
      }
    },
    created() {
    },
    mounted() {
      console.log('echart.vue==>>mounted')
      this.createChart()
      this.clearOptionData()
      this.initPrevData()
    },
    updated(){
      console.log('echart.vue==>>updated')
    },
    destoryed(){
      console.log('echart.vue==>>destoryed')
      if(this.myChart){
        this.myChart.dispose()
      }
    },
    methods: {
      createChart(){
        let ele = document.querySelector('.echarts-wrap #chart-container')
        let wrap = document.querySelector('.echarts-wrap')
        if(ele){
          wrap.innerHTML = ''
        }
        if(window.myChart){
          window.myChart.clear()
          window.myChart = null
        }
        let dom = document.createElement('div')
        dom.id = 'chart-container'
        dom.style.height = '100%'
        wrap.appendChild(dom)
        setTimeout(()=>{
          this.myChart = window.echarts.init(dom, null, {
            locale: 'ZH'
          });
          window.myChart = this.myChart
          console.log('echart.vue==>>createChart, myChart: %o', this.myChart.id)
          let option = this.initOption({
            categoryData: [],
            values: []
          })
          this.myChart.setOption(option, true)
        })
      },
      clearOptionData(){
        if(this.myChart) {
          let option = this.myChart.getOption()
          option.xAxis[0].data = []
          option.series[0].data = []
          option.series[0].name = this.candleType.name
          this.myChart.setOption(option, true)
        }
      },
      initPrevData() {
        this.params.after = `${Date.now()}`
        this.params.before = ''
        this.params.bar = this.candleType.bar
        this.lastTime = this.params.after
        API.getCandles(this.params)
          .then(res => {
            // console.log('echarts.vue==>>initPrevData.getCandles, res: %o', res)
            if(res.data.length) {
              let rawData = res.data
              let categoryData = []
              let values = []
              for (var i = rawData.length - 1; i >= 0; i--) {
                let item = rawData[i]
                categoryData.push(new Date(parseInt(item[0])).Format('MM/dd hh:mm:ss'));
                values.push(this.cleanCandleData(item.slice(1)));
                // volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
              }
              this.$store.commit('user/SET_CUR_PRICE', values[values.length - 1][1])

              let data = {
                categoryData,
                values
              }

              // console.log('echarts.vue==>>initPrevData.getCandles, data: %o', data)

              this.lastTime = rawData[0][0]
              this.appendOptionData(data)
            }
            this.updateChart()
          })
          .catch((err) => {
            console.log('echarts.vue==>>initPrevData.getCandles, err: %o', err)
            setTimeout(() => {
              this.initPrevData()
            }, 5000)
          })
      },
      cleanCandleData(raw){
        let val = []
        val.push(parseFloat(raw[0].replace(',','')))
        val.push(parseFloat(raw[3].replace(',','')))
        val.push(parseFloat(raw[2].replace(',','')))
        val.push(parseFloat(raw[1].replace(',','')))
        return val
      },
      updateChart(){
        setTimeout(()=>{
          this.params.after = ''
          this.params.before = this.lastTime
          API.getCandles(this.params)
          .then(res => {
            // console.log('echarts.vue==>>updateChart.getCandles, res: %o', res)
            if(res.data.length) {
              let rawData = res.data
              let categoryData = []
              let values = []
              for (var i = rawData.length - 1; i >= 0; i--) {
                let item = rawData[i]
                categoryData.push(new Date(parseInt(item[0])).Format('MM/dd hh:mm:ss'));
                values.push(this.cleanCandleData(item.slice(1)));
                // volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
              }

              this.$store.commit('user/SET_CUR_PRICE', values[values.length - 1][1])

              let data = {
                categoryData,
                values
              }

              // console.log('echarts.vue==>>updateChart.getCandles, data: %o', data)

              this.lastTime = rawData[0][0]
              this.appendOptionData(data)
            }

            this.updateChart()
          })
          .catch(() => {
            this.updateChart()
          })
        }, 1000 * 6)
      },
      appendOptionData(data){
        let option = this.myChart.getOption()
        option.xAxis[0].data.push(...data.categoryData)
        option.series[0].data.push(...data.values)
        this.myChart.setOption(option, true)
      },
      initOption(data) {
        let calculateMA = this.calculateMA
        var upColor = '#00C977';
        var downColor = '#E6446B';
        return {
          animation: true,
          backgroundColor: '#13141F',
          // legend: {
          //   // bottom: 10,
          //   show: false,
          //   left: 'center',
          //   data: ['日K'], // 'MA5', 'MA10', 'MA20', 'MA30'],
          //   textStyle: {
          //     color: '#fff'
          //   }
          // },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            borderWidth: 1,
            borderColor: '#ccc',
            padding: 10,
            textStyle: {
              color: '#000'
            },
            position: function (pos, params, el, elRect, size) {
              var obj = { top: 10 };
              obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
              return obj;
            }
          },
          axisPointer: { // 指示坐标轴当前刻度的工具
            // link: { xAxisIndex: 'all' },
            link: { xAxisIndex: [0] },
            label: {
              backgroundColor: '#777'
            }
          },
          toolbox: {
            show: false,
            feature: {
              dataZoom: {
                yAxisIndex: false
              },
              brush: {
                type: ['lineX', 'clear']
              }
            }
          },
          brush: {
            xAxisIndex: 'all',
            brushLink: 'all',
            outOfBrush: {
              colorAlpha: 0.1
            }
          },
          // visualMap: {
          //   show: false,
          //   seriesIndex: 1, //5,
          //   dimension: 2,
          //   pieces: [{
          //     value: 1,
          //     color: downColor
          //   }, {
          //     value: -1,
          //     color: upColor
          //   }]
          // },
          grid: [
            {
              left: '6%',
              right: '8%',
              top: '19%',
              // height: '50%'
              hight: '80%'
            },
            // {
            //   left: '10%',
            //   right: '8%',
            //   top: '83%',
            //   height: '16%'
            // }
          ],
          xAxis: [
            {
              type: 'category',
              data: data.categoryData,
              scale: true,
              boundaryGap: false,
              axisLine: { onZero: false },
              splitLine: { show: false },
              splitNumber: 20,
              min: 'dataMin',
              max: 'dataMax',
              axisPointer: {
                z: 100
              }
            },
            // {
            //   type: 'category',
            //   gridIndex: 1,
            //   data: data.categoryData,
            //   scale: true,
            //   boundaryGap: false,
            //   axisLine: { onZero: false },
            //   axisTick: { show: false },
            //   splitLine: { show: false },
            //   axisLabel: { show: false },
            //   splitNumber: 20,
            //   min: 'dataMin',
            //   max: 'dataMax'
            // }
          ],
          yAxis: [
            {
              scale: true,
              splitLine: false,
              splitArea: {
                show: false
              },
              axisLine:{
                show: true
              },
              axisTick: {
                inside: false
              },
              offset: 5,
              // zlevel: 999
              // nameTextStyle: {
              //   backgroundColor: '#13141F'
              // }
            },
            // {
            //   scale: true,
            //   gridIndex: 1,
            //   splitNumber: 2,
            //   axisLabel: { show: false },
            //   axisLine: { show: false },
            //   axisTick: { show: false },
            //   splitLine: { show: false }
            // }
          ],
          dataZoom: [
            {
              type: 'inside',
              // xAxisIndex: [0, 1],
              xAxisIndex: [0],
              start: 98,
              start: 30,
              end: 100
            },
            // {
            //   show: false,
            //   xAxisIndex: [0, 1],
            //   type: 'slider',
            //   top: '85%',
            //   start: 98,
            //   end: 100
            // }
          ],
          series: [
            {
              name: '日K',
              type: 'candlestick',
              data: data.values,
              clip: true,
              // zlevel: 9,
              itemStyle: {
                color: upColor,
                color0: downColor,
                borderColor: null,
                borderColor0: null
              },
              tooltip: {
                formatter: function (param) {
                  console.log('echarts/index.vue==>> param: %o', param)
                  param = param[0];
                  return [
                    '时间: ' + param.name + '<hr size=1 style="margin: 3px 0">',
                    '开盘: ' + param.data[0] + '<br/>',
                    '收盘: ' + param.data[1] + '<br/>',
                    '最低: ' + param.data[2] + '<br/>',
                    '最高: ' + param.data[3] + '<br/>'
                  ].join('');
                }
              }
            },
            // {
            //   name: 'MA5',
            //   type: 'line',
            //   data: calculateMA(5, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     width: 1,
            //     opacity: 0
            //   }
            // },
            // {
            //   name: 'MA10',
            //   type: 'line',
            //   data: calculateMA(10, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     opacity: 0
            //   }
            // },
            // {
            //   name: 'MA20',
            //   type: 'line',
            //   data: calculateMA(20, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     opacity: 0
            //   }
            // },
            // {
            //   name: 'MA30',
            //   type: 'line',
            //   data: calculateMA(30, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     opacity: 0
            //   }
            // },
            // {
            //   name: '交易量',
            //   type: 'bar',
            //   xAxisIndex: 1,
            //   yAxisIndex: 1,
            //   data: data.volumes
            // }
          ]
        }
      },
      calculateMA(dayCount, data, idx = 0) {
        var result = [];
        for (var i = idx, len = data.values.length; i < len; i++) {
            if (i < dayCount) {
                result.push('-');
                continue;
            }
            var sum = 0;
            for (var j = 0; j < dayCount; j++) {
                sum += data.values[i - j][1];
            }
            result.push(+(sum / dayCount).toFixed(3));
        }
        return result;
      },
    }
  }
</script>
<style lang="scss">
  @import "./index.scss";
</style>
